package com.way.fileexplorer.activities;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.way.fileexplorer.R;
import com.way.fileexplorer.adapters.CopyDestListAdapter;
import com.way.fileexplorer.adapters.FileListAdapter;
import com.way.fileexplorer.fragments.DetailedListFragment;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.StorageUtil;

public class FilePickerActivity extends Activity implements OnItemClickListener {
    private File mTopPath;
    private FileListAdapter mAdapter;
    private boolean bIsSdCard = false;
    private ListView mListView = null;
    private View mEmptyView = null;
    private TextView mPathBar;
    private static String TAG = "FilePickerActivity" ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_paste);
        mListView = (ListView) this.findViewById(R.id.list_paste);
        mListView.setOnItemClickListener(this);
        mEmptyView = (View) this.findViewById(R.id.emptyView);
        mPathBar = (TextView) findViewById(R.id.path_bar_file_explore_activity);
        Intent data = getIntent();
        if (null != data) {
            if (StorageUtil.getExternalStorageState().equals("mounted")){
                DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        bIsSdCard = which == 0?false:true;
                        mTopPath = bIsSdCard ? StorageUtil.getExternalStorage()
                                : StorageUtil.getInternalStorage();
                        mAdapter = FileListAdapter.getFileListAdapter(FilePickerActivity.this,mListView).initWithPath(
                                mTopPath);
                        mPathBar.setText(mAdapter.getCurrentPath().toString());
                        mListView.setAdapter(mAdapter);
                        mListView.setEmptyView(mEmptyView);
                        // Bug 201542 Begin
                        mListView.setOnScrollListener(new FileListScrollListener(mAdapter));
                        // Bug 201542 End
                    }
                };
                setResult(DetailedListFragment.RESULT_RESELECT, null);
                Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.select_destination);
                BaseAdapter adapter = new CopyDestListAdapter();
                builder.setAdapter(adapter, listener);
                // bug 203067 begin
                builder.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if(mTopPath == null){
                            FilePickerActivity.this.finish();
                        }
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                // bug 203067 end
            }else{
                mTopPath = StorageUtil.getInternalStorage();
                mAdapter = FileListAdapter.getFileListAdapter(FilePickerActivity.this,mListView).initWithPath(
                        mTopPath);
                mPathBar.setText(mAdapter.getCurrentPath().toString());
                mListView.setAdapter(mAdapter);
                mListView.setEmptyView(mEmptyView);
                // Bug 201542 Begin
                mListView.setOnScrollListener(new FileListScrollListener(mAdapter));
                // Bug 201542 End
            }
            
        } else {
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        if (mAdapter == null || mAdapter.popupFolder()) {
            super.onBackPressed();
            return;
        }
        mPathBar.setText(mAdapter.getCurrentPath().toString());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
        File file  = mAdapter.getFileList().get(position);
        if(file.isDirectory()){
            mAdapter.execute(position);
            mPathBar.setText(mAdapter.getCurrentPath().toString());
        } else if (file.isFile()) {
            
            String type = FileType.getFileType(FilePickerActivity.this).getTypeByFile(
                    file);
            String requiredType = getIntent().getType();
            //add code
            long size = file.length();
            //add end
            Log.i(TAG,"selected file type is" + type);
            Log.i(TAG,"required Type is" + requiredType);
            //+bug192703
           //Bug 196762 begin
            if((type==null) // bug 209289
                || (requiredType != null && !requiredType.equals("*/*")
                && !requiredType.toLowerCase().equals(type.toLowerCase()))){
                Toast.makeText(this, R.string.file_type_wrong,
                        Toast.LENGTH_SHORT).show();
                return;
            }
          //Bug 196762 end
            //-bug192703
            Uri contentUri = MediaStore.Files.getContentUri("external");
            Cursor cursor = getContentResolver().query(contentUri,
                    new String[] { MediaStore.Files.FileColumns._ID },
                    MediaStore.Files.FileColumns.DATA + "=?",
                    new String[] { file.getPath() }, null);
            Intent intent = new Intent();
            if (cursor != null && cursor.moveToFirst()) {
                Log.i(TAG, "get the content uri");
                long fileId = cursor.getLong(0);
                
                intent.setDataAndType(ContentUris.withAppendedId(contentUri, fileId),type);
                if (getIntent() != null
                        && RingtoneManager.ACTION_RINGTONE_PICKER
                                .equals(getIntent().getAction())) {
                    //add code, filte the file which has no type and the 0kb music file 
                    if((type == null)||(!type.equals("audio/*"))){
                        Toast.makeText(this,R.string.file_type_wrong, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(size == 0){
						Toast.makeText(this, R.string.file_wrong,Toast.LENGTH_SHORT).show();
						return;
			        }
			        //add end
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI,
                            ContentUris.withAppendedId(contentUri, fileId));
                    
                }
                cursor.close();
                if(getIntent() != null && ("android.intent.action.SET_WALLPAPER".equals(getIntent().getAction()) || 
                        "android.intent.action.SET_SPREAD_WALLPAPER".equals(getIntent().getAction()))){
                    if(!type.equals("image/*")){
                        Toast.makeText(this,R.string.file_type_wrong, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    try {
                        int targetId = getIntent().getIntExtra("wallpaper_target_id",0);
                        intent.setAction("com.android.camera.action.CROP");
                        intent.putExtra("set-as-wallpaper", true);
                        intent.putExtra("wallpaper_target_id", targetId);
                        startActivity(intent);
                        finish();
                    } catch (ActivityNotFoundException e) {
                            Toast.makeText(this, R.string.failed_set_wallpaper,
                                    Toast.LENGTH_SHORT).show();
                    }
                    
                }
                
                // Bug 192229 Begin
                // Bug 197712 Begin
                if (getIntent().hasExtra("from_where")
                        && getIntent().getStringExtra("from_where").equals("contact")) {
                // Bug 197712 end
                    if (!type.equals("image/*")) {
                        Toast.makeText(this, R.string.file_type_wrong, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent cropIntent = new Intent("com.android.camera.action.CROP");
                    Uri uri = Uri.fromFile(file);
                    String crop = getIntent().getStringExtra("crop");
                    int aspectX = getIntent().getIntExtra("aspectX", 1);
                    int aspectY = getIntent().getIntExtra("aspectX", 1);
                    int outputX = getIntent().getIntExtra("outputX", 150);
                    int outputY = getIntent().getIntExtra("outputY", 150);
                    boolean return_data = getIntent().getBooleanExtra("return-data", true);
                    Log.d(TAG, "crop = " + crop +
                            " aspectX = " + aspectX +
                            " aspectY = " + aspectY +
                            " outputX = " + outputX +
                            " outputY = " + outputY +
                            " return_data = " + return_data);

                    cropIntent.setDataAndType(uri, "image/*");
                    cropIntent.putExtra("crop", crop);
                    cropIntent.putExtra("aspectX", aspectX);
                    cropIntent.putExtra("aspectY", aspectY);
                    cropIntent.putExtra("outputX", outputX);
                    cropIntent.putExtra("outputY", outputY);
                    cropIntent.putExtra("return-data", return_data);
                    startActivityForResult(cropIntent, 0);
                    return;
                }
                // Bug 192229 End
                if(getIntent().hasExtra(MediaStore.EXTRA_OUTPUT)){
                    Log.i(TAG,"has EXTRA_OUTPUT");
//                    intent = getIntent();
                    intent.setAction("com.android.camera.action.CROP");
                    intent.setDataAndType(ContentUris.withAppendedId(contentUri, fileId),type);
                    intent.putExtra("crop", "true");
                    intent.putExtra("scale", true);
                    intent.putExtra("scaleUpIfNeeded", true);
                    intent.putExtra("aspectX", 1);
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("outputX", getIntent().getIntExtra("outputX", 100));
                    intent.putExtra("outputY", getIntent().getIntExtra("outputX", 100));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,(Uri)getIntent().getSerializableExtra(MediaStore.EXTRA_OUTPUT));
                    startActivity(intent);
                    finish();
                }
            } else {
                if(cursor != null){
                    cursor.close();
                }
                Log.i(TAG, file + "not in mediaprovider, get the file uri");
                intent.setDataAndType(Uri.parse("file://" + file.getPath()),type);
                if (getIntent() != null
                        && RingtoneManager.ACTION_RINGTONE_PICKER
                                .equals(getIntent().getAction())) {
                    //add code,filte the "file" type(*.tar.gz) for the ringtone 
                    if(!type.equals("audio/*")){
                        Toast.makeText(this,R.string.file_type_wrong, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //add end
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI,
                            Uri.parse("file://" + file.getPath()));
                }
            }
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    // Bug 192229 Begin
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    Log.d(TAG, "resultCode != RESULT_OK ");
                }
                break;
            default:
                Log.d(TAG, "requestCode not implement ");
                break;
        }
    }
    // Bug 192229 End
}
